package com.treeliked.netdiskdemo.controller;

import com.treeliked.netdiskdemo.model.AuthEntity;
import com.treeliked.netdiskdemo.model.Response;
import com.treeliked.netdiskdemo.model.ResultCode;
import com.treeliked.netdiskdemo.model.dataobject.User;
import com.treeliked.netdiskdemo.model.param.UserQueryParam;
import com.treeliked.netdiskdemo.service.UserService;
import com.treeliked.netdiskdemo.util.AuthConstant;
import com.treeliked.netdiskdemo.util.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * user control
 *
 * @author lqs2
 * @date 2018/12/5, Wed
 */
@RestController
@RequestMapping("/api/user")
public class UserController {


    private final UserService userService;

    private static Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/login")
    public Response login(@RequestBody UserQueryParam queryUser, HttpServletResponse response) {
        String name = queryUser.getUsername();
        String pwd = queryUser.getPassword();
        log.info("{}, {}...", name, pwd);

        Response resp = new Response();
        resp.setCode(ResultCode.SUCCESS);
        try {
            User user = userService.hasMatchUser(name, pwd);
            if (user != null) {
                resp.setMessage("1");
                // 生成token 并返回
                String token = JwtUtils.createDefaultToken(AuthConstant.AUTH_KEY_OF_USER_ID, user.getId());

                resp.setData(new AuthEntity(user.getId(), token));

                // 写入cookie
                Cookie cookie = new Cookie(AuthConstant.AUTH_KEY_OF_TOKEN_ID, token);
                cookie.setPath("/");
                cookie.setMaxAge(AuthConstant.TOKEN_VALID_AGE);

                response.addCookie(cookie);
            } else {
                resp.setMessage("0");
            }
        } catch (Exception e) {
            log.error("", e);
            resp.setCode(ResultCode.INTERNAL_SERVER_ERROR);
            resp.setMessage(e.getMessage());
        }
        return resp;
    }

}
